# Create your views here.
import json
from datetime import date

import django_redis
from django.core.paginator import Paginator, EmptyPage
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from haystack.views import SearchView

from apps.contents.models import ContentCategory
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from utils.goods import get_categories, get_breadcrumb, get_goods_specs
from utils.views import LoginRequiredJsonMixin


class IndexView(View):
    def get(self, request):
        categories = get_categories()

        # 渲染模板的上下文
        context = {
            'categories': categories,

        }
        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 渲染模板的上下文
        context = {
            'categories': categories,
            'contents': contents,
        }
        return render(request, 'index.html', context)


class ListView(View):
    def get(self, request, category_id):

        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        if not all([page, page_size, ordering]):
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        breadcrumb = get_breadcrumb(category)

        try:
            skus = SKU.objects.filter(category_id=category_id).order_by(ordering)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '查询异常'})

        paginator = Paginator(skus, page_size)

        try:
            page_skus = paginator.page(page)
        except EmptyPage:
            return JsonResponse({'code': 400,
                                 'errmsg': '查询异常'})
        total_page = paginator.num_pages

        list = []
        for sku in page_skus.object_list:
            list.append(
                {
                    'id': sku.id,
                    'name': sku.name,
                    'default_image_url': sku.default_image.url,
                    'price': sku.price
                }
            )

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,
            'list': list,
            'count': total_page
        })


class HotGoodsView(View):

    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]
        hot_skus = []

        for sku in skus:
            hot_skus.append(
                {
                    'id': sku.id,
                    'default_image_url': sku.default_image.url,
                    'name': sku.name,
                    'price': sku.price
                }
            )
        return JsonResponse(data={
            "code": "0",
            "errmsg": "OK",
            "hot_skus": hot_skus
        })


class SKUSearchView(SearchView):
    def create_response(self):
        context = self.get_context()

        data_list = []
        for sku in context['page'].object_list:
            data_list.append(
                {
                    'id': sku.object.id,
                    'name': sku.object.name,
                    'price': sku.object.price,
                    'default_image_url': sku.object.default_image.url,
                    'searchkey': context.get('query'),
                    'page_size': context['page'].paginator.num_pages,
                    'count': context['page'].paginator.count
                }
            )

        return JsonResponse(data=data_list, safe=False)


class DetailView(View):
    def get(self, request, sku_id):

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        categories = get_categories()

        breadcrumb = get_breadcrumb(sku.category)

        goods_specs = get_goods_specs(sku)

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'goods_specs': goods_specs,
        }

        return render(request, 'detail.html', context)


class DetailVisitView(View):
    def post(self, request, category_id):

        try:
            gc = GoodsCategory.objects.get(id=category_id)

        except GoodsCategory.DoesNotExist:
            return JsonResponse(data={'code': 400, 'errmsg': '参数错误'})

        today = date.today()

        try:
            gvc = GoodsVisitCount.objects.get(category=gc, date=today)
        except GoodsVisitCount.DoesNotExist:

            GoodsVisitCount.objects.create(category=gc, date=today, count=1)
        else:
            gvc.count += 1
            gvc.save()

        return JsonResponse({'code': 0, 'errmsg': 'OK'})


class UserBrowseHistory(LoginRequiredJsonMixin, View):

    def post(self, request):
        data = json.loads(request.body.decode())

        sku_id = data.get('sku_id')

        try:
            sku = SKU.objects.get(id=sku_id)

        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        redis_client = django_redis.get_redis_connection('history')

        user = request.user
        redis_client.lrem(f'history_{user.id}', 0, sku.id)
        redis_client.lpush(f'history_{user.id}', sku.id)
        redis_client.ltrim(f'history_{user.id}', 0, 4)

        return JsonResponse(data={'code': 400, 'errmsg': 'ok'})

    def get(self, request):
        redis_client = django_redis.get_redis_connection('history')

        user = request.user
        sku_ids = redis_client.lrange(f'history_{user.id}', 0, -1)

        # 根据sku_ids列表数据，查询出商品sku信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        return JsonResponse(data={'code': 0, 'errmsg': 'OK', 'skus': skus},safe=False)
